<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\index\controller;

use app\common\controller\Apicommon;
use app\common\controller\Excel;
use app\index\model\Device;
use app\index\model\DeviceCategory;
use app\index\model\Door;
use app\index\model\GearRecord;
use app\index\model\MemberRecord;
use app\index\model\UnusualRecord;
use app\user\model\User;
use hongmo\Hongmo;
use think\App;
use think\helper\Hash;
use think\Db;

/**
 * 前台首页控制器
 * @package app\index\controller
 */
class Index extends Apicommon
{
    use Excel;

    public function initialize()
    {
//        parent::initialize();
        header('Access-Control-Allow-Headers: content-type,authorization,token');
        header('Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS');
        header('Access-Control-Allow-Origin: *');
        if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
            echo 1;die;
        }
        // 默认跳转模块
        if('login' !== $this->request->action() && empty(session('user_auth.uid'))){
            $this->redirect('login');
        }else{
            $this->uid = session('user_auth.uid');
        }

        if ('/' == $this->request->baseUrl()) {
            $this->redirect(url('index/index/index'));
        }
    }

    public function index()
    {
        // 默认跳转模块
        if(empty(session('user_auth.uid'))){
            $this->redirect('login');
        }
        $this->assign('session',session('user_auth'));
        return $this->fetch();
     }
    //登录
    public function login()
    {
        if ($_POST){
            $username = trim(input('username'));
            $password = trim(input('password'));
            if (empty($username) || empty($password)) {
                return $this->ajaxReturn(0,'用户名或密码不能为空');
            }
            // 匹配登录方式
            if (preg_match("/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/", $username)) {
                // 邮箱登录
                $map['email'] = $username;
            } elseif (preg_match("/^1\d{10}$/", $username)) {
                // 手机号登录
                $map['mobile'] = $username;
            } else {
                // 用户名登录
                $map['username'] = $username;
            }
            $map['status'] = 1;
            // 查找用户
            $user = User::get($map);

            if (!$user) {
                $this->error ( '用户不存在或被禁用！');
            } else {
                if (!Hash::check((string)$password, $user['password'])) {
                    $this->error('账号或者密码错误！');
                } else {
                    // 更新登录信息
                    $user['last_login_time'] = request()->time();
                    $user['last_login_ip'] = request()->ip(1);
                    if ($user->save()) {
                        $auth = array(
                            'uid'             => $user->id,
                            'group'           => $user->group,
                            'role'            => $user->role,
                            'role_name'       => Db::name('admin_role')->where('id', $user->role)->value('name'),
                            'avatar'          => $user->avatar,
                            'username'        => $user->username,
                            'nickname'        => $user->nickname,
                            'last_login_time' => $user->last_login_time,
                            'last_login_ip'   => get_client_ip(1),
                        );
                        session('user_auth', $auth);
                        return $this->ajaxReturn(0,'登录成功');
                    }
                }
            }
        }
        return $this->fetch();
    }

    public function welcome()
    {
        $table_data = [
            'user_num' => \app\index\model\User::count('id'),
            'device_num' => Device::count('id'),
            'overhaul_num' => Device::where([
                ['warning_time', '<=', date('Y-m-d')],
                ['status', 'neq', 6], // 排除已报废的设备
                ['status', 'neq', 4]  // 排除安检中的设备
            ])->count(),
            'unusual_num' => UnusualRecord::where('read', 0)->count('id'),
            'gear_record_num' => GearRecord::where(1)->count('id'),
            'use_record_num' => db('used_record')->count('id'),
        ];

        // 最近30天取用/归还记录
        // 查询一个月内第一个时间点
        $day_start = GearRecord::field('createtime')->whereTime('createtime','between',['last month','today'])->order('createtime','asc')->limit(1)->value('createtime');

        $get_record = [];
        $back_record = [];
        $record_group = [];
        if (!empty($day_start)) {
            $day_start = strtotime(date('Y-m-d',$day_start));
            $day_end = strtotime(date('Y-m-d',$day_start) . ' +1 day');
            while ($day_end < time()) {
                $record_group[] = $day_start;
                $get_temp = GearRecord::whereTime('createtime','between',[$day_start,$day_end])->where('action',1)->count('id');
                $back_temp = GearRecord::whereTime('createtime','between',[$day_start,$day_end])->where('action',2)->count('id');
                $get_record[] = !empty($get_temp) ? $get_temp : 0;
                $back_record[] = !empty($back_temp) ? $back_temp : 0;
                $day_start = $day_end;
                $day_end = strtotime(date('Y-m-d',$day_end) . ' +1 day');
            }
            $get_temp = GearRecord::whereTime('createtime','>',$day_start)->where('action',1)->count('id');
            $back_temp = GearRecord::whereTime('createtime','>',$day_start)->where('action',2)->count('id');
            $get_record[] = !empty($get_temp) ? $get_temp : 0;
            $back_record[] = !empty($back_temp) ? $back_temp : 0;
            $record_group[] = $day_start;
        }
        $arr_record_group = [];
        foreach ($record_group as $group_item) {
            $arr_record_group[] = "'".date('m月d日',$group_item)."'";
        }
        $arr_record_group = implode(',',$arr_record_group);

        // 设备实时使用情况
        $device_chart = [
            'in_use' => Device::where('status',1)->count('id'),
            'in_charge' => Device::where('status',2)->count('id'),
            'free' => Device::where('status',3)->count('id'),
            'in_check' => Device::where('status',4)->count('id'),
            'wait_check' => Device::where('warning_time','<',date('Y-m-d'))->count('id')
        ];

        $this->assign('device_chart',$device_chart);
        $this->assign('table_data',$table_data);
        $this->assign('get_record',json_encode($get_record,JSON_UNESCAPED_UNICODE));
        $this->assign('back_record',json_encode($back_record,JSON_UNESCAPED_UNICODE));
        $this->assign('record_group',$arr_record_group);
        $this->assign('session',session('user_auth'));
        return $this->fetch();
    }

    public function grade_add()
    {
        if ($_POST){
            $grade_name = trim(input('grade_name'));
            $leader = trim(input('leader'));
            $mobile = trim(input('mobile'));
            if (empty($grade_name) || empty($leader) || empty($mobile)){
                return $this->ajaxReturn(1,'有必填项未填写');
            }
            $name_check = db('grade')->where('grade_name',$grade_name)->find();
            if (!empty($name_check)) {
                return $this->ajaxReturn(1,$grade_name . ' 名字已存在');
            }
            $data['grade_name'] = $grade_name;
            $data['leader'] = $leader;
            $data['mobile'] = $mobile;
//        dump($data);die;
            $res = Db::name('grade')->insertGetId($data);
            if ($res){
                return $this->ajaxReturn(0,'新增成功');
            }
            return $this->ajaxReturn(1,'新增失败');
        }
        return $this->fetch();
    }

    public function grade_edit()
    {
        $id = input('id');
        if (empty($id)){
            return $this->ajaxReturn(1,'缺少参数');
        }
        if ($_POST){
            $grade_name = trim(input('grade_name'));
            $leader = trim(input('leader'));
            $mobile = trim(input('mobile'));
            if (empty($grade_name) || empty($leader) || empty($mobile)){
                return $this->ajaxReturn(1,'有必填项未填写');
            }
            $name_check = db('grade')->where([['grade_name','=',$grade_name],['id','<>',$id]])->find();
            if (!empty($name_check)) {
                return $this->ajaxReturn(1,$grade_name . ' 名字已存在');
            }
            $data['grade_name'] = $grade_name;
            $data['leader'] = $leader;
            $data['mobile'] = $mobile;
//        dump($data);die;
            $res = Db::name('grade')->where('id',$id)->update($data);
            if ($res){
                return $this->ajaxReturn(0,'新增成功');
            }
            return $this->ajaxReturn(1,'新增失败');
        }
        $grade = Db::name('grade')->where('id',$id)->find();
        $this->assign('grade',$grade);
        return $this->fetch();

    }

    public function grade_list()
    {
        $grade_name = trim(input('grade_name'));
        $leader = trim(input('leader'));
        $mobile = trim(input('mobile'));
        $where = [];
        if (!empty($grade_name)){
            $where[] = ['grade_name','like','%' . $grade_name . '%'];
        }
        if (!empty($leader)){
            $where[] = ['leader','like','%' . $leader . '%'];
        }
        if (!empty($mobile)){
            $where[] = ['mobile','like','%' . $mobile . '%'];
        }


        // 记录搜索条件，用于导出Excel
        session('grade_list_condition', $where);

        $data = Db::name('grade')->where($where)->order('id','asc')->paginate(5,false,['query'=>$this->request->param()]);
        $result['data'] = $data;
        $result['count'] = Db::name('grade')->where($where)->count('id');
        $this->assign('page',$data->render());
        $this->assign('data',$data->items());
        return $this->fetch();
    }
    /**
     * 导入班组信息
     */
    public function grade_list_import()
    {
        $data = $this->parseExcel([
            '班组名称' => 'grade_name',
            '负责人' => 'leader',
            '联系电话' => 'mobile',
        ]);
        $insert_count = 0;
        foreach ($data as $datum) {
            // 检查设备编号
            $check_device = db('grade')->get(['grade_name' => $datum['grade_name']]);
            if ($check_device) {
                return $this->ajaxReturn(1,$datum['grade_name'] . ' 这个班组已存在,不能导入。已成功导入 ' . $insert_count . ' 条数据');
            }
            $temp['grade_name'] = trim($datum['grade_name']);
            $temp['leader'] = trim($datum['leader']);
            $temp['mobile'] = trim($datum['mobile']);
            db('grade')->insert($temp);
            $insert_count++;
        }
        return $this->ajaxReturn(0,'成功导入 ' . $insert_count . ' 条数据');
    }
    /**
     * 导出班组信息
     */
    public function grade_list_export()
    {
        $condition = session('grade_list_condition')?:[];
        $grade = Db::name('grade')->where($condition)->order('id', 'asc')->select();
        $data = [];
        foreach ($grade as $key => $value) {
            $temp = [];
            $temp['grade_name'] = $value['grade_name'];
            $temp['leader'] = $value['leader'];
            $temp['mobile'] = $value['mobile'];
            $data[] = $temp;
        }
        $this->exportExcel('班组信息', [
            '班组名称',
            '负责人',
            '联系电话',
        ], $data);
    }

    public function grade_del()
    {
        $id = input('id');
        if (empty($id)){
            return $this->ajaxReturn(1,'缺少参数');
        }
        $ids = explode(',',$id);
        // 检查用户
        $user_check = \app\index\model\User::whereIn('grade_id',$ids)->count('id');
        if (!empty($user_check)) {
            return $this->ajaxReturn(1,'该班组还有'.intval($user_check).'个用户,不能删除该班组');
        }
        $res = Db::name('grade')->whereIn('id',$ids)->delete();
        if ($res){
            return $this->ajaxReturn(0,'删除成功');
        }
        return $this->ajaxReturn(1,'删除失败');
    }
    public function member_list()
    {
        $this->request->filter('trim');
        $page = input('page') ?: 1;
        $where = [];
        $username = input('username');
        if (!empty($username)){
            $where[] = ['username','like','%'.$username.'%'];
        }
        $mobile = input('mobile');
        if (!empty($mobile)){
            $where[] = ['mobile','like','%'.$mobile.'%'];
        }
        $grade_name = input('grade_name');
        if (!empty($grade_name)){
            $grade_id = Db::name('grade')->where('grade_name',$grade_name)->value('id');
            if (!empty($grade_id))
            $where[] = ['grade_id','eq',$grade_id];
        }
        $start_time = input('start');
        if (!empty($start_time)){
            $where[] = ['entry_time','>=',$start_time];
        }
        $end_time = input('end');
        if (!empty($end_time)){
            $where[] = ['entry_time','<=',$end_time];
        }

        // 记录搜索条件，用于导出Excel
        session('member_list_cond', $where);

        $member = Db::name('member_user')->order('id','asc')->where($where)->order('id','asc')->paginate(10,false,['query'=>$this->request->param()])->each(function ($item){
            $item['device_cate_text'] = '';
            if (!empty($item['device_cate'])) {
                $cate = DeviceCategory::whereIn('id',$item['device_cate'])->column('name');
                if (!empty($cate))
                    $item['device_cate_text'] = implode(',',$cate);
            }
            return $item;
        });
        $row = $member->items();
        foreach ($row as $key => $value){
            $row[$key]['grade'] = Db::name('grade')->where('id',$value['grade_id'])->value('grade_name');
            if ($value['iris']){
                $row[$key]['status'] = '已录入';
            }else{
                $row[$key]['status'] = '未录入';
            }
        }
        $grade = Db::name('grade')->field('id,grade_name')->select();
        $this->assign('grade',$grade);
        $this->assign('member',$row);
        $this->assign('pages',$member->render());
        return $this->fetch();
    }
    public function member_list_export()
    {
        $where = session('member_list_cond') ?: [];
        $member = Db::name('member_user')->where($where)->order('id','asc')->select();
        $data = [];
        foreach ($member as $key => $value){
            $temp = [];
            $temp['user_serial'] = $value['user_serial'];
            $temp['username'] = $value['username'];
            $temp['mobile'] = $value['mobile'];
            $temp['position'] = $value['position'];
            $temp['entry_time'] = $value['entry_time'];
            $temp['status'] = $value['iris'] ? '已录入':'未录入';
            $temp['grade'] = Db::name('grade')->where('id',$value['grade_id'])->value('grade_name');
            $data[] = $temp;
        }
        $this->exportExcel('人员信息',[
            '用户编号',
            '姓名',
            '手机号',
            '职位',
            '入职时间',
            '是否录入虹膜',
            '所属班组',
        ],$data);
    }
    public function member_list_import()
    {
        $data = $this->parseExcel([
            '用户编号'=>'user_serial',
            '姓名'=>'username',
            '手机号'=>'mobile',
            '职位'=>'position',
            '入职时间'=>'entry_time',
            '所属班组'=>'grade',
        ]);

        $insert_count = 0;
        foreach ($data as $datum) {
            $check_user = \app\index\model\User::get(['user_serial'=>$datum['user_serial']]);
            if ($check_user) $this->error_json($datum['user_serial'].'这个编号已存在,不能导入。已成功导入 '.$insert_count.' 条数据');

            $temp['user_serial'] = $datum['user_serial'];
            $temp['username'] = $datum['username'];
            $temp['mobile'] = $datum['mobile'];
            $temp['entry_time'] = $datum['entry_time'];
            $temp['grade_id'] = Db::name('grade')->where('grade_name',$datum['grade'])->value('id');
            $temp['position'] = $datum['position'];
            \app\index\model\User::create($temp);
            $insert_count++;
        }
        $this->success_json('成功导入 '.$insert_count.' 条数据');
    }
    public function member_add()
    {
        if ($_POST){
            $grade_id = input('grade_id');
            $username = input('username');
            $user_serial = input('user_serial');
            $mobile = input('mobile');
            $position = input('position');
            $entry_time = input('entry_time');
            $device_cate = input('device_cate');
            if (empty($grade_id) || empty($username) || empty($mobile) || empty($position) ||empty($entry_time)){
                return $this->ajaxReturn(1,'必填项未填写');
            }
            if (empty($device_cate))
                return $this->ajaxReturn(1,'至少分配一种设备');
            $serial_check = \app\index\model\User::get(['user_serial'=>$user_serial]);
            if ($serial_check) {
                return $this->ajaxReturn(1,$user_serial . ' 编号已存在，请更换编号');
            }

            $res = Db::name('member_user')->insertGetId([
                'username'=>$username,
                'user_serial'=>$user_serial,
                'grade_id'=>$grade_id,
                'mobile'=>$mobile,
                'position'=>$position,
                'device_cate'=>trim($device_cate,','),
                'entry_time'=>$entry_time,
                'create_time'=>time()
                ]);
            if($res){
                return $this->ajaxReturn(0,'新增员工成功');
            }
            return $this->ajaxReturn(1,'新增员工失败');
        }
        $device_category = DeviceCategory::all();
        $this->assign('device_category',$device_category);
        $grade = Db::name('grade')->field('id,grade_name')->select();
        $this->assign('grade',$grade);
        return $this->fetch();
    }
    public function member_edit()
    {
        $id = input('id');
        if (empty($id)){
            return $this->ajaxReturn(1,'缺少参数');
        }
        if ($_POST){
            $grade_id = input('grade_id');
            $username = input('username');
            $mobile = input('mobile');
            $position = input('position');
            $entry_time = input('entry_time');
            $device_cate = input('device_cate');
            if (empty($grade_id) || empty($username) || empty($mobile) || empty($position) ||empty($entry_time)){
                return $this->ajaxReturn(1,'必填项未填写');
            }
            if (empty($device_cate))
                return $this->ajaxReturn(1,'至少分配一种设备');
            $res = Db::name('member_user')->where('id',$id)->update([
                'username'=>$username,
                'grade_id'=>$grade_id,
                'mobile'=>$mobile,
                'position'=>$position,
                'entry_time'=>$entry_time,
                'device_cate'=>trim($device_cate,','),
                'create_time'=>time()
            ]);
            if($res !== false){
                return $this->ajaxReturn(0,'编辑员工成功');
            }
            return $this->ajaxReturn(1,'编辑员工失败');
        }
        $device_category = DeviceCategory::all();
        $this->assign('device_category',$device_category);
        $member = Db::name('member_user')->where('id',$id)->find();
        $grade = Db::name('grade')->field('id,grade_name')->select();
        $this->assign('grade',$grade);
        $this->assign('member',$member);
        return $this->fetch();
    }
    public function member_del()
    {
        $id = input('id');
        if (empty($id)){
            return $this->ajaxReturn(1,'缺少参数');
        }
        $ids = explode(',',$id);
        $res = Db::name('member_user')->whereIn('id',$ids)->delete();
        foreach ($ids as $value){
            $hongmo = new Hongmo();
            $hongmo->delmoabn($value);
        }
        if ($res){
            return $this->ajaxReturn(0,'删除成功');
        }
        return $this->ajaxReturn(1,'删除失败');
    }
    public function iris_add()
    {
        $id = input('id');
        $user = \app\index\model\User::get($id);
        if ($_POST){
            if (empty($user)) $this->error_json('用户不存在');
            // 查询是否已设置过虹膜
            if (!empty($user->iris)) $this->error_json('该用户已设置过虹膜，不能重复设置');

            // 录入虹膜信息
            $hongmo = new Hongmo();
            $result = $hongmo->zhuceyongh($id);

            if ($result){
                $user->iris = $id;
                $user->save();
                $this->success_json('设置成功');
            }
            $this->error_json($hongmo->getError());
        }
        if (empty($user)) exit('用户不存在');
        $has_iris = !empty($user->iris) ? true : false;
        $this->assign('id',$id);
        $this->assign('has_iris',$has_iris);
        return $this->fetch();
    }
    public function iris_del()
    {
        if (!$this->request->isPost()) {
            die('请求有误');
        }
        $id = input('id');
        $user = \app\index\model\User::get($id);
        if (empty($user)) $this->error_json('用户不存在');
        // 查询是否已设置过虹膜
        if (empty($user->iris)) $this->error_json('该用户未设置过虹膜信息');

        // 删除虹膜信息
        $hongmo = new Hongmo();
        $result = $hongmo->delmoabn($id);

        if ($result){
            $user->iris = null;
            $user->save();
            $this->success_json('删除成功');
        }
        $this->error_json($hongmo->getError());
    }

    // 虹膜设备
    public function gear_iris_add()
    {
        if ($_POST){
            $port = input('port');
            $serial = input('serial');
            if (empty($port) || empty($serial)){
                return $this->ajaxReturn(1,'必填项未填写');
            }
            if (strlen($port) < 3 || mb_substr($port,0,3) !== "com" || !preg_match("/^com[\d]+$/",$port)) {
                return $this->ajaxReturn(1, '端口号格式应为：com + 数字');
            }
            $iris_check = db('iris')->where('iris_serial',$serial)->whereOr('port',$port)->find();
            if (!empty($iris_check)) {
                return $this->ajaxReturn(1,'编号或串口号被占用');
            }
            $res = Db::name('iris')->insertGetId([
                'port'=>$port,
                'iris_serial'=>$serial
            ]);
            if ($res){
                return $this->ajaxReturn(0,'添加成功');
            }
            return $this->ajaxReturn(1,'添加失败');
        }
        return $this->fetch();
    }
    public function gear_iris_list()
    {
        $iris = Db::name('iris')->order('iris_serial','asc')->paginate(input('limit',10));
        $this->assign('pages',$iris->render());
        $this->assign('list',$iris->items());
        return $this->fetch();
    }
    public function gear_iris_edit()
    {
        $id = input('id');
        if (empty($id)) {
            return $this->ajaxReturn(1, '缺少参数');
        }
        if ($_POST) {
            $port = input('port');
            $serial = input('serial');
            if (empty($port) || empty($serial)) {
                return $this->ajaxReturn(1, '必填项未填写');
            }
            if (!is_numeric($serial)) {
                return $this->ajaxReturn(1, '设备编号请填数字');
            }
            if (strlen($port) < 3 || mb_substr($port,0,3) !== "com" || !preg_match("/^com[\d]+$/",$port)) {
                return $this->ajaxReturn(1, '端口号格式应为：com + 数字');
            }

            // 冲突检查
            $iris_check = db('iris')->where([
                ['iris_serial', '=', $serial],
                ['id', '<>', $id]
            ])->whereOr(function ($query) use ($id, $port) {
                $query->where([
                    ['port', '=', $port],
                    ['id', '<>', $id]
                ]);
            })->find();
            if (!empty($iris_check)) {
                return $this->ajaxReturn(1, '编号或串口号被占用');
            }
            $res = Db::name('iris')->where('id', $id)->update([
                'port' => $port,
                'iris_serial' => $serial
            ]);
            if ($res !== false) {
                return $this->ajaxReturn(0, '编辑成功');
            }
            return $this->ajaxReturn(1, '编辑失败');
        }
        $iris = Db::name('iris')->where('id', $id)->find();
        $this->assign('iris', $iris);
        return $this->fetch();
    }
    public function gear_iris_del()
    {
        $id = input('id');
        if (empty($id)){
            return $this->ajaxReturn(1,'缺少参数');
        }
        $ids = explode(',',$id);
        $num_check = db('iris')->count('id');
        if ($num_check <= count($ids)) {
            return $this->ajaxReturn(1,'设备不能全部删除，请至少保留1台设备');
        }
        $gear_check = db('gear')->where('iris_id',$id)->find('id');
        if (!empty($gear_check)) {
            return $this->ajaxReturn(1,'有柜子和该识别仪绑定中，不能删除');
        }
        $res = Db::name('iris')->whereIn('id',$ids)->delete();
        if ($res){
            return $this->ajaxReturn(0,'删除成功');
        }
        return $this->ajaxReturn(1,'删除失败');
    }

}
